﻿using System;
using System.Collections.Generic;
using System.Text;

namespace BGShell.Collections
{
    public sealed class HashSet<T> : ICollection<T>
    {
        private readonly Dictionary<T, Object> _dict;

        public HashSet()
        {
            _dict = new Dictionary<T, Object>();
        }

        public HashSet(IEqualityComparer<T> comparer)
        {
            _dict = new Dictionary<T, Object>(comparer);
        }

        public bool Add(T item)
        {
            if (!_dict.ContainsKey(item))
            {
                _dict.Add(item, null);
                return true;
            }

            return false;
        }

        public bool AddRange(IEnumerable<T> items)
        {
            bool changed = false;

            foreach (var item in items)
            {
                changed |= Add(item);
            }

            return changed;
        }

        void ICollection<T>.Add(T item)
        {
            _dict[item] = null;
        }

        public void Clear()
        {
            _dict.Clear();
        }

        public bool Contains(T item)
        {
            return _dict.ContainsKey(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _dict.Keys.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _dict.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(T item)
        {
            return _dict.Remove(item);
        }

        public bool RemoveRange(IEnumerable<T> items)
        {
            bool changed = false;

            foreach (var item in items)
            {
                changed |= _dict.Remove(item);
            }

            return changed;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _dict.Keys.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _dict.Keys.GetEnumerator();
        }
    }
}
